<?php
/***
* @version $Id: usercp_register.php 336 2007-01-23 08:12:56Z flexiondotorg $
* @copyright (c) 2006 - 2007 Flexion.Org
*            (c) 2006              kkroo < princeomz2004@hotmail.com > (Omar Ramadan) http://phpbb-login.sourceforge.net
*            (c) 2006              Afterlife_69 < afterlife_69@hotmail.com > (Dean Newman) http://www.ugboards.com
*            (c) 2004 - 2005 Falstaff < david@falstaffenterprises.com > (David Falstaff) http://www.falstaffenterprises.com
*            (c) 2004 - 2005 Project Minerva
*            (c) 2001 - 2006 phpBB Group
* @license   http://opensource.org/licenses/gpl-license.php GNU Public License
***/

if ( !defined('IN_R3BORN') )
{
	die('Hacking attempt');
}

$unhtml_specialchars_match = array('#&gt;#', '#&lt;#', '#&quot;#', '#&amp;#');
$unhtml_specialchars_replace = array('>', '<', '"', '&');
$server_url = generate_website_url() . append_sid('register.' . $phpEx);

loadHooks(getHooks('profile'));

$error = FALSE;
$error_msg = '';
$page_title = $lang['Edit_profile'];

//
// Check and initialize some variables if needed
//
if (isset($_POST['submit']) || isset($_POST['avatargallery']) || isset($_POST['submitavatar']) || isset($_POST['cancelavatar']) )
{
	include($root_path . 'includes/functions_validate.'.$phpEx);
	include($root_path . 'includes/functions_bbcode.'.$phpEx);
	include($root_path . 'includes/functions_message.'.$phpEx);

	$user_id = intval($_POST['user_id']);
	$current_email = trim(htmlspecialchars($_POST['current_email']));
	$email_confirm = trim(htmlspecialchars($_POST['email_confirm']));

	$strip_var_list = array('email' => 'email', 'email_confirm' => 'email_confirm', 'icq' => 'icq', 'aim' => 'aim', 'msn' => 'msn', 'yim' => 'yim', 'website' => 'website', 'location' => 'location', 'occupation' => 'occupation', 'interests' => 'interests');//, 'confirm_code' => 'confirm_code');

	// Strip all tags from data ... may p**s some people off, bah, strip_tags is
	// doing the job but can still break HTML output ... have no choice, have
	// to use htmlspecialchars ... be prepared to be moaned at.
	while( list($var, $param) = @each($strip_var_list) )
	{
		$$var = get_var($param, '');
	}

	$username = ( !empty($_POST['username']) ) ? r3born_clean_username($_POST['username']) : '';

	$trim_var_list = array('cur_password' => 'cur_password', 'new_password' => 'new_password', 'password_confirm' => 'password_confirm', 'signature' => 'signature');

	while( list($var, $param) = @each($trim_var_list) )
	{
		if ( !empty($_POST[$param]) )
		{
			$$var = trim($_POST[$param]);
		}
	}

	$signature = (isset($signature)) ? str_replace('<br />', "\n", $signature) : '';
	$signature_bbcode_uid = '';

	// Run some validation on the optional fields. These are pass-by-ref, so they'll be changed to
	// empty strings if they fail.
	validate_optional_fields($icq, $aim, $msn, $yim, $website, $location, $occupation, $interests, $signature);

	$sid = get_var('sid', 0);

### R3-born - ADD
#
	$hooks->execute('editprofile-init-vars');
#
### R3-born - END ADD

	$attachsig = ( isset($_POST['attachsig']) ) ? ( ($_POST['attachsig']) ? TRUE : 0 ) : $userdata['user_attachsig'];
	$allowhtml = ( isset($_POST['allowhtml']) ) ? ( ($_POST['allowhtml']) ? TRUE : 0 ) : $userdata['user_allowhtml'];
	$allowbbcode = ( isset($_POST['allowbbcode']) ) ? ( ($_POST['allowbbcode']) ? TRUE : 0 ) : $userdata['user_allowbbcode'];
	$allowsmilies = ( isset($_POST['allowsmilies']) ) ? ( ($_POST['allowsmilies']) ? TRUE : 0 ) : $userdata['user_allowsmile'];
	$user_style = ( isset($_POST['style']) ) ? intval($_POST['style']) : $config['default_style'];
	if ( !empty($_POST['language']) )
	{
		if ( preg_match('/^[a-z_]+$/i', $_POST['language']) )
		{
			$user_lang = htmlspecialchars($_POST['language']);
		}
		else
		{
			$error = true;
			$error_msg = $lang['Fields_empty'];
		}
	}
	else
	{
		$user_lang = $config['default_lang'];
	}
	$user_timezone = ( isset($_POST['timezone']) ) ? doubleval($_POST['timezone']) : $config['board_timezone'];
	$user_dst = ( isset($_POST['dst']) ) ? intval($_POST['dst']) : 0;

	// SIMPLE COLORED USERGROUPS MOD START
	if ( is_array($color_groups['groupdata']) )
	{
		$matched = false;
		$group_priority = ( isset($_POST['group_priority']) ) ? intval($_POST['group_priority']) : 0;
		foreach($color_groups['groupdata'] AS $color_group)
		{
			if ( is_array($color_group['group_users']) )
			{
				if ( in_array($userdata['user_id'], $color_group['group_users']) && $color_group['group_id'] == $group_priority )
				{
					$matched = true;
				}
			}
		}
		if ( ! $matched )
		{
			$group_priority = 0;
		}
	}
	else
	{
		$group_priority = 0;
	}
	// COLOR GROUPS END
	$user_dateformat = ( !empty($_POST['dateformat']) ) ? trim(htmlspecialchars($_POST['dateformat'])) : $config['default_dateformat'];
	$user_avatar_local = ( isset($_POST['avatarselect']) && !empty($_POST['submitavatar']) && $config['allow_avatar_local'] ) ? htmlspecialchars($_POST['avatarselect']) : ( ( isset($_POST['avatarlocal'])  ) ? htmlspecialchars($_POST['avatarlocal']) : '' );
	$user_avatar_category = ( isset($_POST['avatarcatname']) && $config['allow_avatar_local'] ) ? htmlspecialchars($_POST['avatarcatname']) : '' ;
	$user_avatar_remoteurl = ( !empty($_POST['avatarremoteurl']) ) ? trim(htmlspecialchars($_POST['avatarremoteurl'])) : '';
	$user_avatar_upload = ( !empty($_POST['avatarurl']) ) ? trim($_POST['avatarurl']) : ( ( $_FILES['avatar']['tmp_name'] != "none") ? $_FILES['avatar']['tmp_name'] : '' );
	$user_avatar_name = ( !empty($_FILES['avatar']['name']) ) ? $_FILES['avatar']['name'] : '';
	$user_avatar_size = ( !empty($_FILES['avatar']['size']) ) ? $_FILES['avatar']['size'] : 0;
	$user_avatar_filetype = ( !empty($_FILES['avatar']['type']) ) ? $_FILES['avatar']['type'] : '';
	$user_gravatar_email = ( !empty($_POST['gravatar_email']) ) ? trim(htmlspecialchars($_POST['gravatar_email'])) : '';	// Gravatar MOD
	$user_avatar = ( empty($user_avatar_local)) ? $userdata['user_avatar'] : '';
	$user_avatar_type = ( empty($user_avatar_local)) ? $userdata['user_avatar_type'] : '';

	$viewemail = ( isset($_POST['viewemail']) ) ? ( ($_POST['viewemail']) ? TRUE : 0 ) : 0;
	$allowviewonline = ( isset($_POST['hideonline']) ) ? ( ($_POST['hideonline']) ? 0 : TRUE ) : TRUE;

	if ( (isset($_POST['avatargallery']) || isset($_POST['submitavatar']) || isset($_POST['cancelavatar'])) && (!isset($_POST['submit'])) )
	{
		$username = stripslashes($username);
		$email = stripslashes($email);
		$email_confirm = stripslashes($email_confirm);
		$cur_password = htmlspecialchars(stripslashes($cur_password));
		$new_password = htmlspecialchars(stripslashes($new_password));
		$password_confirm = htmlspecialchars(stripslashes($password_confirm));

		$icq = stripslashes($icq);
		$aim = stripslashes($aim);
		$msn = stripslashes($msn);
		$yim = stripslashes($yim);

		$website = stripslashes($website);
		$location = stripslashes($location);
		$occupation = stripslashes($occupation);
		$interests = stripslashes($interests);
		$signature = htmlspecialchars(stripslashes($signature));

		$user_lang = stripslashes($user_lang);
		$user_dateformat = stripslashes($user_dateformat);

		if ( !isset($_POST['cancelavatar']))
		{
			$user_avatar = $user_avatar_category . '/' . $user_avatar_local;
			$user_avatar_type = USER_AVATAR_GALLERY;
		}
	}
}

//
// Did the user submit? In this case build a query to update the users profile in the DB
//
if ( isset($_POST['submit']) )
{
	include($root_path . 'includes/usercp/usercp_avatar.'.$phpEx);

	// session id check - added in phpBB 2.0.22 but appears not to work. Comment out for the time being.
	/*
	if ($sid == '' || $sid != $userdata['session_id'])
	{
		$error = true;
		$error_msg .= (!empty($error_msg)) ? '<br />' . $lang['Session_invalid'] : $lang['Session_invalid'];
	}
	*/

	$passwd_sql = '';

### R3-born - ADD (User Self Delete)
#
	//if( isset($_POST['deleteuser']) && ( $_GET['mode'] == 'editprofile' || $_POST['mode'] == 'editprofile' ) && $userdata['user_level'] == USER )
	if( isset($_POST['deleteuser']) && ($user_id == $userdata['user_id'] && $userdata['user_level'] == USER) )
	{
    	loadHooks(getHooks('user'));

		include_once($root_path . 'includes/functions_user.' . $phpEx);
		$this_userdata = $userdata;
		delete_user($user_id);
		unset($this_userdata);

		$message = $lang['User_deleted'] . '<br /><br />' . sprintf($lang['Click_return_index'], '<a href="' . append_sid("index.$phpEx") . '">', '</a>');
		message_die(GENERAL_MESSAGE, $message);
	}
	elseif( isset($_POST['deleteuser']) && ($user_id != $userdata['user_id'] || $userdata['user_level'] > 0 ) )
	{
		message_die(GENEARL_MESSAGE, $lang['User_delete_not_allowed']);
	}
#
### R3-born - END ADD

	if ( $user_id != $userdata['user_id'] )
	{
		$error = TRUE;
		$error_msg .= ( ( isset($error_msg) ) ? '<br />' : '' ) . $lang['Wrong_Profile'];
	}
	else if ( $email != $email_confirm )
	{
		$error = TRUE;
		$error_msg .= ( ( isset($error_msg) ) ? '<br />' : '' ) . $lang['Email_mismatch'];
	}

	$passwd_sql = '';
	if ( !empty($new_password) && !empty($password_confirm) )
	{
		if ( $new_password != $password_confirm )
		{
			$error = TRUE;
			$error_msg .= ( ( isset($error_msg) ) ? '<br />' : '' ) . $lang['Password_mismatch'];
		}
		else if ( strlen($new_password) > 32 )
		{
			$error = TRUE;
			$error_msg .= ( ( isset($error_msg) ) ? '<br />' : '' ) . $lang['Password_long'];
		}
		else
		{
			$sql = "SELECT user_password
					FROM " . USERS_TABLE . "
					WHERE user_id = $user_id";
			if ( !($result = $db->sql_query($sql)) )
			{
				message_die(GENERAL_ERROR, 'Could not obtain user_password information', '', __LINE__, __FILE__, $sql);
			}

			$row = $db->sql_fetchrow($result);

			if ( $row['user_password'] != md5($cur_password) )
			{
				$error = TRUE;
				$error_msg .= ( ( isset($error_msg) ) ? '<br />' : '' ) . $lang['Current_password_mismatch'];
			}

			if ( !$error )
			{
				$new_password = md5($new_password);
				$passwd_sql = "user_password = '$new_password', ";
			}
		}
	}
	else if ( ( empty($new_password) && !empty($password_confirm) ) || ( !empty($new_password) && empty($password_confirm) ) )
	{
		$error = TRUE;
		$error_msg .= ( ( isset($error_msg) ) ? '<br />' : '' ) . $lang['Password_mismatch'];
	}

	//
	// Do a ban check on this email address
	//

	if ( $email != $userdata['user_email'] || $email_confirm != $userdata['user_email'] || $email != $email_confirm )
	{
		$result = validate_email($email);
		if ( $result['error'] )
		{
			$email = $userdata['user_email'];

			$email_confirm = $userdata['user_email'];
			$email = $email_confirm;

			$error = TRUE;
			$error_msg .= ( ( isset($error_msg) ) ? '<br />' : '' ) . $result['error_msg'];
		}
		else if ( $email != $email_confirm )
		{
			$error = TRUE;
			$error_msg .= ( ( isset($error_msg) ) ? '<br />' : '' ) . $lang['Email_mismatch'];
		}


		$sql = "SELECT user_password
				FROM " . USERS_TABLE . "
				WHERE user_id = $user_id";
		if ( !($result = $db->sql_query($sql)) )
		{
			message_die(GENERAL_ERROR, 'Could not obtain user_password information', '', __LINE__, __FILE__, $sql);
		}

		$row = $db->sql_fetchrow($result);

		if ( $row['user_password'] != md5($cur_password) )
		{
			$email = $userdata['user_email'];

			$email_confirm = $userdata['user_email'];
			$email = $email_confirm;

			$error = TRUE;
			$error_msg .= ( ( isset($error_msg) ) ? '<br />' : '' ) . $lang['Current_password_mismatch'];
		}
	}

	$username_sql = '';
	if ( $config['allow_namechange'] )
	{
		if ( empty($username) )
		{
			// Error is already triggered, since one field is empty.
			$error = TRUE;
		}
		else if ( $username != $userdata['username'] )
		{
			if (strtolower($username) != strtolower($userdata['username']) )
			{
				$result = validate_username($username);
				if ( $result['error'] )
				{
					$error = TRUE;
					$error_msg .= ( ( isset($error_msg) ) ? '<br />' : '' ) . $result['error_msg'];
				}
			}

			if (!$error)
			{
				$username_sql = "username = '" . str_replace("\'", "''", $username) . "', ";
			}
		}
	}

	if ( $signature != '' )
	{
		if ( strlen($signature) > $config['max_sig_chars'] )
		{
			$error = TRUE;
			$error_msg .= ( ( isset($error_msg) ) ? '<br />' : '' ) . $lang['Signature_too_long'];
		}

		if ( !isset($signature_bbcode_uid) || $signature_bbcode_uid == '' )
		{
			$signature_bbcode_uid = ( $allowbbcode ) ? make_bbcode_uid() : '';
		}
		$signature = prepare_message($signature, $allowhtml, $allowbbcode, $allowsmilies, $signature_bbcode_uid);
	}

	if ( $website != '' )
	{
		rawurlencode($website);
	}

	$avatar_sql = '';

	if ( isset($_POST['avatardel']) )
	{
		$avatar_sql = user_avatar_delete($userdata['user_avatar_type'], $userdata['user_avatar']);
	}
	elseif ( ( !empty($user_avatar_upload) || !empty($user_avatar_name) ) && $config['allow_avatar_upload'] )
	{
		if ( !empty($user_avatar_upload) )
		{
			$avatar_mode = (empty($user_avatar_name)) ? 'remote' : 'local';
			$avatar_sql = user_avatar_upload($avatar_mode, $userdata['user_avatar'], $userdata['user_avatar_type'], $error, $error_msg, $user_avatar_upload, $user_avatar_name, $user_avatar_size, $user_avatar_filetype);
		}
		else if ( !empty($user_avatar_name) )
		{
			$l_avatar_size = sprintf($lang['Avatar_filesize'], round($config['avatar_filesize'] / 1024));

			$error = true;
			$error_msg .= ( ( !empty($error_msg) ) ? '<br />' : '' ) . $l_avatar_size;
		}
	}
	else if ( $user_avatar_remoteurl != '' && $config['allow_avatar_remote'] )
	{
		user_avatar_delete($userdata['user_avatar_type'], $userdata['user_avatar']);
		$avatar_sql = user_avatar_url($error, $error_msg, $user_avatar_remoteurl);
	}
	else if ( $user_avatar_local != '' && $config['allow_avatar_local'] )
	{
		user_avatar_delete($userdata['user_avatar_type'], $userdata['user_avatar']);
		$avatar_sql = user_avatar_gallery($error, $error_msg, $user_avatar_local, $user_avatar_category);
	}
	// Gravatar MOD
	else if ( $user_gravatar_email != '' && $config['allow_gravatar'] )
	{
		user_avatar_delete($userdata['user_avatar_type'], $userdata['user_avatar']);
		include_once($root_path . 'includes/functions_gravatar.'.$phpEx);
		$avatar_sql = user_gravatar($error, $error_msg, $user_gravatar_email);
	}

	if ( !$error )
	{
		/*if ( $avatar_sql == '' )
		{
			$avatar_sql = ( $mode == 'editprofile' ) ? '' : "'', " . USER_AVATAR_NONE;
		}*/

		if ( $email != $userdata['user_email'] && $config['require_activation'] != USER_ACTIVATION_NONE && $userdata['user_level'] != ADMIN )
		{
			$user_active = 0;
			$user_actkey = gen_rand_string(true);
			$key_len = 54 - ( strlen($server_url) );
			$key_len = ( $key_len > 6 ) ? $key_len : 6;
			$user_actkey = substr($user_actkey, 0, $key_len);

			if ( $userdata['session_logged_in'] )
			{
				session_end($userdata['session_id'], $userdata['user_id']);
			}
		}
		else
		{
			$user_active = 1;
			$user_actkey = '';
		}

		$sql = "UPDATE " . USERS_TABLE . "
				SET " . $username_sql . $passwd_sql . "user_email = '" . str_replace("\'", "''", $email) ."', user_icq = '" . str_replace("\'", "''", $icq) . "', user_website = '" . str_replace("\'", "''", $website) . "', user_occ = '" . str_replace("\'", "''", $occupation) . "', user_from = '" . str_replace("\'", "''", $location) . "', user_interests = '" . str_replace("\'", "''", $interests) . "', user_sig = '" . str_replace("\'", "''", $signature) . "', user_sig_bbcode_uid = '$signature_bbcode_uid', user_viewemail = $viewemail, user_aim = '" . str_replace("\'", "''", str_replace(' ', '+', $aim)) . "', user_yim = '" . str_replace("\'", "''", $yim) . "', user_msnm = '" . str_replace("\'", "''", $msn) . "', user_attachsig = $attachsig, user_allowsmile = $allowsmilies, user_allowhtml = $allowhtml, user_allowbbcode = $allowbbcode, user_allow_viewonline = $allowviewonline, group_priority = '$group_priority', user_timezone = $user_timezone, user_dst = $user_dst, user_dateformat = '" . str_replace("\'", "''", $user_dateformat) . "', user_lang = '" . str_replace("\'", "''", $user_lang) . "', user_style = $user_style, user_active = $user_active, user_actkey = '" . str_replace("\'", "''", $user_actkey) . "'" . $avatar_sql . "
				WHERE user_id = $user_id";

		if ( !($result = $db->sql_query($sql)) )
		{
			message_die(GENERAL_ERROR, 'Could not update users table', '', __LINE__, __FILE__, $sql);
		}

### R3-born - ADD
#
		$hooks->execute('editprofile-update-vars', $user_id);
#
### R3-born - END ADD

		// If the name was changed some module may need to update there tables - NOT IMPLEMENTED YET - TODO - TO DO
		/*
		if ($username_sql != '')
		{
			$hooks->execute('editprofile-change-name', $user_id, $username);
		}
		*/

		// We remove all stored login keys since the password has been updated
		// and change the current one (if applicable)
		if ( !empty($passwd_sql) )
		{
			session_reset_keys($user_id, $user_ip);
		}

		if ( !$user_active )
		{
			//
			// The users account has been deactivated, send them an email with a new activation key
			//
			include($root_path . 'includes/class_emailer.'.$phpEx);
			$emailer = new emailer($config['smtp_delivery']);

			if ( $config['require_activation'] != USER_ACTIVATION_ADMIN )
			{
				$emailer->from($config['board_email']);
				$emailer->replyto($config['board_email']);

 				$emailer->use_template('user_activate', stripslashes($user_lang));
 				$emailer->email_address($email);
 				$emailer->set_subject($lang['Reactivate']);

 				$emailer->assign_vars(array(
 					'SITENAME' => $config['sitename'],
 					'USERNAME' => preg_replace($unhtml_specialchars_match, $unhtml_specialchars_replace, substr(str_replace("\'", "'", $username), 0, 25)),
 					'EMAIL_SIG' => (!empty($config['board_email_sig'])) ? str_replace('<br />', "\n", "-- \n" . $config['board_email_sig']) : '',

 					'U_ACTIVATE' => $server_url . '?mode=activate&' . POST_USERS_URL . '=' . $user_id . '&act_key=' . $user_actkey)
 				);
 				$emailer->send();
 				$emailer->reset();
 			}
			else if ( $config['require_activation'] == USER_ACTIVATION_ADMIN )
			{
				$sql = 'SELECT user_email, user_lang
 						FROM ' . USERS_TABLE . '
 						WHERE user_level = ' . ADMIN;

				if ( !($result = $db->sql_query($sql)) )
				{
					message_die(GENERAL_ERROR, 'Could not select Administrators', '', __LINE__, __FILE__, $sql);
				}

				while ($row = $db->sql_fetchrow($result))
				{
					$emailer->from($config['board_email']);
					$emailer->replyto($config['board_email']);
					$emailer->email_address(trim($row['user_email']));
					$emailer->use_template("admin_activate", $row['user_lang']);
					$emailer->set_subject($lang['Reactivate']);

					$emailer->assign_vars(array(
						'USERNAME' => preg_replace($unhtml_specialchars_match, $unhtml_specialchars_replace, substr(str_replace("\'", "'", $username), 0, 25)),
						'EMAIL_SIG' => str_replace('<br />', "\n", "-- \n" . $config['board_email_sig']),

						'U_ACTIVATE' => $server_url . '?mode=activate&' . POST_USERS_URL . '=' . $user_id . '&act_key=' . $user_actkey)
					);
					$emailer->send();
					$emailer->reset();
				}
				$db->sql_freeresult($result);
			}

			$message = $lang['Profile_updated_inactive'] . '<br /><br />' . sprintf($lang['Click_return_index'],  '<a href="' . append_sid("index.$phpEx") . '">', '</a>');
		}
		else
		{
			$message = $lang['Profile_updated'] . '<br /><br />' . sprintf($lang['Click_return_index'],  '<a href="' . append_sid("index.$phpEx") . '">', '</a>');
		}

		$template->assign_vars(array(
			"META" => '<meta http-equiv="refresh" content="5;url=' . append_sid("index.$phpEx") . '">')
		);

		message_die(GENERAL_MESSAGE, $message);

	}
} // End of submit


if ( $error )
{
	//
	// If an error occured we need to stripslashes on returned data
	//
	$username = stripslashes($username);
	$email = stripslashes($email);
	$email_confirm = stripslashes($email_confirm);

	$cur_password = '';
	$new_password = '';
	$password_confirm = '';

	$icq = stripslashes($icq);
	$aim = str_replace('+', ' ', stripslashes($aim));
	$msn = stripslashes($msn);
	$yim = stripslashes($yim);

	$website = stripslashes($website);
	$location = stripslashes($location);
	$occupation = stripslashes($occupation);
	$interests = stripslashes($interests);
	$signature = stripslashes($signature);
	$signature = ($signature_bbcode_uid != '') ? preg_replace("/:(([a-z0-9]+:)?)$signature_bbcode_uid(=|\])/si", '\\3', $signature) : $signature;

	$user_lang = stripslashes($user_lang);
	$user_dateformat = stripslashes($user_dateformat);

}
else if ( !isset($_POST['avatargallery']) && !isset($_POST['submitavatar']) && !isset($_POST['cancelavatar']) )
{
	$user_id = $userdata['user_id'];
	$username = $userdata['username'];
	$email = $userdata['user_email'];
	$email_confirm = $userdata['user_email'];
	$cur_password = '';
	$new_password = '';
	$password_confirm = '';

	$icq = $userdata['user_icq'];
	$aim = str_replace('+', ' ', $userdata['user_aim']);
	$msn = $userdata['user_msnm'];
	$yim = $userdata['user_yim'];

	$website = $userdata['user_website'];
	$location = $userdata['user_from'];
	$occupation = $userdata['user_occ'];
	$interests = $userdata['user_interests'];
	$signature_bbcode_uid = $userdata['user_sig_bbcode_uid'];
	$signature = ($signature_bbcode_uid != '') ? preg_replace("/:(([a-z0-9]+:)?)$signature_bbcode_uid(=|\])/si", '\\3', $userdata['user_sig']) : $userdata['user_sig'];

	$viewemail = $userdata['user_viewemail'];

	$attachsig = $userdata['user_attachsig'];
	$allowhtml = $userdata['user_allowhtml'];
	$allowbbcode = $userdata['user_allowbbcode'];
	$allowsmilies = $userdata['user_allowsmile'];
	$allowviewonline = $userdata['user_allow_viewonline'];

	$user_avatar = ( $userdata['user_allowavatar'] ) ? $userdata['user_avatar'] : '';
	$user_avatar_type = ( $userdata['user_allowavatar'] ) ? $userdata['user_avatar_type'] : USER_AVATAR_NONE;

	$user_style = $userdata['user_style'];
	$user_lang = $userdata['user_lang'];
	$user_timezone = $userdata['user_timezone'];
	$user_dateformat = $userdata['user_dateformat'];
	$user_dst = $userdata['user_dst'];

### R3-born - ADD
#
	$hooks->execute('editprofile-get-vars');
#
### R3-born - END ADD

}

page_header($page_title);


// SIMPLE COLORED USERGROUPS MOD START
$group_drop_down = '';
if ( is_array($color_groups['groupdata']) )
{
	$group_values = '';
	$group_count = 0;
	foreach($color_groups['groupdata'] AS $color_group)
	{
		if ( in_array($userdata['user_id'], $color_group['group_users']) )
		{
			$group_priority_selected = ( $userdata['group_priority'] == $color_group['group_id'] ) ? ' selected="selected"' : '';
			$group_values .= '<option value="' . $color_group['group_id'] . '"' . $group_priority_selected . '>' . $color_group['group_name'] . '</option>';
			$group_count++;
		}
	}
	if ( $group_values && $group_count > 1)
	{
		$group_drop_down = '<select name="group_priority">' . $group_values . '</select>';
		$template->assign_block_vars('switch_color_groups', array());
	}
	else
	{
		$group_priority = 0;
	}
}
else
{
	$group_drop_down = '';
}
// COLOR GROUPS END

if ( $user_id != $userdata['user_id'] )
{
	$error = TRUE;
	$error_msg = $lang['Wrong_Profile'];
}

if( isset($_POST['avatargallery']) && !$error )
{
	include($root_path . 'includes/usercp/usercp_avatar.'.$phpEx);

	$avatar_category = ( !empty($_POST['avatarcategory']) ) ? htmlspecialchars($_POST['avatarcategory']) : '';

	$template->set_filenames(array(
		'body' => 'profile_avatar_gallery.tpl')
	);

	$allowviewonline = !$allowviewonline;

	//display_avatar_gallery($mode, $avatar_category, $user_id, $email, $current_email, $coppa, $username, $email, $new_password, $cur_password, $password_confirm, $icq, $aim, $msn, $yim, $website, $location, $occupation, $interests, $signature, $viewemail, $notifypm, $popup_pm, $notifyreply, $attachsig, $allowhtml, $allowbbcode, $allowsmilies, $allowviewonline, $user_style, $user_lang, $user_timezone, $user_dateformat, $userdata['session_id']);
	display_avatar_gallery($avatar_category, $user_id, $email, $current_email, $email_confirm, $username, $email, $new_password, $cur_password, $password_confirm, $icq, $aim, $msn, $yim, $website, $location, $occupation, $interests, $signature, $viewemail, $attachsig, $allowhtml, $allowbbcode, $allowsmilies, $allowviewonline, $user_style, $user_lang, $user_timezone, $user_dateformat, $userdata['session_id']);
}
else
{
	include($root_path . 'includes/functions_selects.'.$phpEx);

/*
	if ( !isset($coppa) )
	{
		$coppa = FALSE;
	}
*/

	if ( !isset($user_style) )
	{
		$user_style = $config['default_style'];
	}

	$avatar_img = '';
	if ( $user_avatar_type )
	{
		switch( $user_avatar_type )
		{
			case USER_AVATAR_UPLOAD:
				$avatar_img = ( $config['allow_avatar_upload'] ) ? '<img src="' . $config['avatar_path'] . '/' . $user_avatar . '" alt="" />' : '';
				break;
			case USER_AVATAR_REMOTE:
				$avatar_img = ( $config['allow_avatar_remote'] ) ? '<img src="' . $user_avatar . '" alt="" />' : '';
				break;
			case USER_AVATAR_GALLERY:
				$avatar_img = ( $config['allow_avatar_local'] ) ? '<img src="' . $config['avatar_gallery_path'] . '/' . $user_avatar . '" alt="" />' : '';
				break;
			// Gravatar MOD
			case USER_GRAVATAR:
				include_once($root_path . 'includes/functions_gravatar.'.$phpEx);
				$avatar_img = gravatar_output($user_avatar);
				$gravatar_mail = $user_avatar;
				break;
		}
	}

	//$s_hidden_fields = '<input type="hidden" name="mode" value="' . $mode . '" /><input type="hidden" name="agreed" value="true" /><input type="hidden" name="coppa" value="' . $coppa . '" />';
	$s_hidden_fields = '<input type="hidden" name="mode" value="' . $mode . '" />';
	//<input type="hidden" name="agreed" value="true" />';
	$s_hidden_fields .= '<input type="hidden" name="sid" value="' . $userdata['session_id'] . '" />';

	$s_hidden_fields .= '<input type="hidden" name="user_id" value="' . $userdata['user_id'] . '" />';
	$s_hidden_fields .= '<input type="hidden" name="current_email" value="' . $userdata['user_email'] . '" />';

	if ( !empty($user_avatar_local) )
	{
		$s_hidden_fields .= '<input type="hidden" name="avatarlocal" value="' . $user_avatar_local . '" /><input type="hidden" name="avatarcatname" value="' . $user_avatar_category . '" />';
	}

	$html_status =  ( $userdata['user_allowhtml'] && $config['allow_html'] ) ? $lang['HTML_is_ON'] : $lang['HTML_is_OFF'];
	$bbcode_status = ( $userdata['user_allowbbcode'] && $config['allow_bbcode']  ) ? $lang['BBCode_is_ON'] : $lang['BBCode_is_OFF'];
	$smilies_status = ( $userdata['user_allowsmile'] && $config['allow_smilies']  ) ? $lang['Smilies_are_ON'] : $lang['Smilies_are_OFF'];

	if ( $error )
	{
		$template->set_filenames(array(
			'reg_header' => 'error_body.tpl')
		);
		$template->assign_vars(array(
			'ERROR_MESSAGE' => $error_msg)
		);
		$template->assign_var_from_handle('ERROR_BOX', 'reg_header');
	}

	$template->set_filenames(array(
		'body' => 'profile_edit_body.tpl')
	);

	$template->assign_block_vars('switch_self_delete', array());

	if ($config['allow_namechange'])
	{
		$template->assign_block_vars('switch_namechange_allowed', array());
	}
	else
	{
		$template->assign_block_vars('switch_namechange_disallowed', array());
	}

	//
	// Let's do an overall check for settings/versions which would prevent
	// us from doing file uploads....
	//
	$form_enctype = ( !@ini_get('file_uploads') || !$config['allow_avatar_upload'] ) ? '' : 'enctype="multipart/form-data"';

	$template->assign_vars(array(
		'USERNAME' => isset($username) ? $username : '',
		'CUR_PASSWORD' => isset($cur_password) ? $cur_password : '',
		'NEW_PASSWORD' => isset($new_password) ? $new_password : '',
		'PASSWORD_CONFIRM' => isset($password_confirm) ? $password_confirm : '',
		'EMAIL' => isset($email) ? $email : '',
		'CONFIRM_IMG' => $confirm_image,
		'YIM' => $yim,
		'ICQ' => $icq,
		'MSN' => $msn,
		'AIM' => $aim,
		'OCCUPATION' => $occupation,
		'INTERESTS' => $interests,
		'LOCATION' => $location,
		'WEBSITE' => $website,
		'SIGNATURE' => str_replace('<br />', "\n", $signature),
		'VIEW_EMAIL_YES' => ( $viewemail ) ? 'checked="checked"' : '',
		'VIEW_EMAIL_NO' => ( !$viewemail ) ? 'checked="checked"' : '',
		'HIDE_USER_YES' => ( !$allowviewonline ) ? 'checked="checked"' : '',
		'HIDE_USER_NO' => ( $allowviewonline ) ? 'checked="checked"' : '',
		'ALWAYS_ADD_SIGNATURE_YES' => ( $attachsig ) ? 'checked="checked"' : '',
		'ALWAYS_ADD_SIGNATURE_NO' => ( !$attachsig ) ? 'checked="checked"' : '',
		'ALWAYS_ALLOW_BBCODE_YES' => ( $allowbbcode ) ? 'checked="checked"' : '',
		'ALWAYS_ALLOW_BBCODE_NO' => ( !$allowbbcode ) ? 'checked="checked"' : '',
		'ALWAYS_ALLOW_HTML_YES' => ( $allowhtml ) ? 'checked="checked"' : '',
		'ALWAYS_ALLOW_HTML_NO' => ( !$allowhtml ) ? 'checked="checked"' : '',
		'ALWAYS_ALLOW_SMILIES_YES' => ( $allowsmilies ) ? 'checked="checked"' : '',
		'ALWAYS_ALLOW_SMILIES_NO' => ( !$allowsmilies ) ? 'checked="checked"' : '',
		'DST_YES' => ($user_dst) ? 'checked="checked"' : '',
        'DST_NO' => (!$user_dst) ? 'checked="checked"' : '',
		'ALLOW_AVATAR' => $config['allow_avatar_upload'],
		'AVATAR' => $avatar_img,
		'AVATAR_SIZE' => $config['avatar_filesize'],
		'LANGUAGE_SELECT' => language_select($user_lang, 'language'),
		'STYLE_SELECT' => style_select($user_style, 'style'),
		'TIMEZONE_SELECT' => tz_select($user_timezone, 'timezone'),
	    'DATE_FORMAT' => date_select($user_dateformat,'dateformat'),
		// SIMPLE COLORED USERGROUPS MOD START
		'GROUP_PRIORITY_SELECT' => $group_drop_down,
		// COLOR GROUPS END
		'HTML_STATUS' => $html_status,
		'BBCODE_STATUS' => sprintf($bbcode_status, '<a href="' . append_sid("help.$phpEx?mode=bbcode") . '" target="_bbcode">', '</a>'),
		'SMILIES_STATUS' => $smilies_status,

		'BREADCRUMB_REG_OR_EDIT' => $lang['Profile'],

		'L_DELETE_USER' => $lang['User_delete'], 					// Self delete MOD
		'L_DELETE_USER_EXPLAIN' => $lang['User_delete_explain'],	// Self delete MOD
		'GRAVATAR_MAIL' => ($gravatar_mail) ? $gravatar_mail : '',	// Gravatar MOD

		'L_CURRENT_PASSWORD' => $lang['Current_password'],
		'L_NEW_PASSWORD' => $lang['New_password'],
		'L_CONFIRM_PASSWORD' => $lang['Confirm_password'],
		'L_CONFIRM_PASSWORD_EXPLAIN' => $lang['Confirm_password_explain'],
		'L_PASSWORD_IF_CHANGED' => $lang['password_if_changed'],
		'L_PASSWORD_CONFIRM_IF_CHANGED' => $lang['password_confirm_if_changed'],
		'L_SUBMIT' => $lang['Submit'],
		'L_RESET' => $lang['Reset'],
		'L_ICQ_NUMBER' => $lang['ICQ'],
		'L_MESSENGER' => $lang['MSNM'],
		'L_YAHOO' => $lang['YIM'],
		'L_WEBSITE' => $lang['Website'],
		'L_AIM' => $lang['AIM'],
		'L_LOCATION' => $lang['Location'],
		'L_OCCUPATION' => $lang['Occupation'],
		'L_BOARD_LANGUAGE' => $lang['Board_lang'],
		'L_BOARD_STYLE' => $lang['Board_style'],
		'L_TIMEZONE' => $lang['Timezone'],
		'L_DATE_FORMAT' => $lang['Date_format'],
		'L_DATE_FORMAT_EXPLAIN' => $lang['Date_format_explain'],
		'L_DST'=> $lang['DST'],

		// SIMPLE COLORED USERGROUPS MOD START
		'L_GROUP_PRIORITY' => $lang['Group_priority'],
		// COLOR GROUPS END
		'L_YES' => $lang['Yes'],
		'L_NO' => $lang['No'],
		'L_INTERESTS' => $lang['Interests'],
		'L_ALWAYS_ALLOW_SMILIES' => $lang['Always_smile'],
		'L_ALWAYS_ALLOW_BBCODE' => $lang['Always_bbcode'],
		'L_ALWAYS_ALLOW_HTML' => $lang['Always_html'],
		'L_HIDE_USER' => $lang['Hide_user'],
		'L_ALWAYS_ADD_SIGNATURE' => $lang['Always_add_sig'],

		'L_AVATAR_PANEL' => $lang['Avatar_panel'],
		'L_AVATAR_EXPLAIN' => sprintf($lang['Avatar_explain'], $config['avatar_max_width'], $config['avatar_max_height'], (round($config['avatar_filesize'] / 1024))),
		'L_UPLOAD_AVATAR_FILE' => $lang['Upload_Avatar_file'],
		'L_UPLOAD_AVATAR_URL' => $lang['Upload_Avatar_URL'],
		'L_UPLOAD_AVATAR_URL_EXPLAIN' => $lang['Upload_Avatar_URL_explain'],
		'L_AVATAR_GALLERY' => $lang['Select_from_gallery'],
		'L_AVATAR_GALLERY_BREADCRUMB' => $lang['Avatar_gallery'],
		'L_SHOW_GALLERY' => $lang['View_avatar_gallery'],
		'L_LINK_REMOTE_AVATAR' => $lang['Link_remote_Avatar'],
		'L_LINK_REMOTE_AVATAR_EXPLAIN' => $lang['Link_remote_Avatar_explain'],

		// Gravatar MOD
		'L_GRAVATAR_PANEL' => $lang['Gravatar_panel'],
		'L_GRAVATAR_EMAIL' => $lang['Gravatar_email'],
		'L_DELETE_AVATAR' => $lang['Delete_Image'],
		'L_CURRENT_IMAGE' => $lang['Current_Image'],

		'L_SIGNATURE' => $lang['Signature'],
		'L_SIGNATURE_EXPLAIN' => sprintf($lang['Signature_explain'], $config['max_sig_chars']),
		'L_PREFERENCES' => $lang['Preferences'],
		'L_PUBLIC_VIEW_EMAIL' => $lang['Public_view_email'],
		'L_ITEMS_REQUIRED' => $lang['Items_required'],
		'L_REGISTRATION_INFO' => $lang['Registration_info'],
		'L_PROFILE_INFO' => $lang['Profile_info'],
		'L_PROFILE_INFO_NOTICE' => $lang['Profile_info_warn'],
		'L_EMAIL_ADDRESS' => $lang['Email_address'],

		'L_CONFIRM_EMAIL' => $lang['Email_confirm'],
		'EMAIL_CONFIRM' => $email_confirm,

		'L_CONFIRM_CODE_IMPAIRED'	=> sprintf($lang['Confirm_code_impaired'], '<a href="mailto:' . $config['board_email'] . '">', '</a>'),
		'L_CONFIRM_CODE'			=> $lang['Confirm_code'],
		'L_CONFIRM_CODE_EXPLAIN'	=> $lang['Confirm_code_explain'],

		'S_ALLOW_AVATAR_UPLOAD' => $config['allow_avatar_upload'],
		'S_ALLOW_AVATAR_LOCAL' => $config['allow_avatar_local'],
		'S_ALLOW_AVATAR_REMOTE' => $config['allow_avatar_remote'],
		'S_ALLOW_GRAVATAR' => $config['allow_gravatar'],	// Gravatar MOD
		'S_HIDDEN_FIELDS' => $s_hidden_fields,
		'S_FORM_ENCTYPE' => $form_enctype,
		'S_PROFILE_ACTION' => append_sid("profile.$phpEx"))
	);

	//Only display the hook driven options and switch style block when the user is logged in, ie not registering.
	if ($userdata['session_logged_in'])
	{
		$hooks->execute('editprofile-display-options');

		//Only show the change style option if the it is not being overidden by the admin
		if (!$config['override_user_style'])
    	{
	    	$template->assign_block_vars('switch_user_style_block', array());
    	}
	}

	//
	// This is another cheat using the block_var capability
	// of the templates to 'fake' an IF...ELSE...ENDIF solution
	// it works well :)
	//
	if ( $userdata['user_allowavatar'] && !$config['allow_gravatar_only'] && ( $config['allow_avatar_upload'] || $config['allow_avatar_local'] || $config['allow_avatar_remote'] || $config['allow_gravatar']) )
	{
		$template->assign_block_vars('switch_avatar_block', array() );

		if ( $config['allow_avatar_upload'] && file_exists(@realpath('./' . $config['avatar_path'])) )
		{
			if ( $form_enctype != '' )
			{
				$template->assign_block_vars('switch_avatar_block.switch_avatar_local_upload', array() );
			}
			$template->assign_block_vars('switch_avatar_block.switch_avatar_remote_upload', array() );
		}

		if ( $config['allow_avatar_remote'] )
		{
			$template->assign_block_vars('switch_avatar_block.switch_avatar_remote_link', array() );
		}

		if ( $config['allow_avatar_local'] && file_exists(@realpath('./' . $config['avatar_gallery_path'])) )
		{
			$template->assign_block_vars('switch_avatar_block.switch_avatar_local_gallery', array() );
		}

		// Gravatar MOD
		if ( $config['allow_gravatar'] )
		{
			$template->assign_block_vars('switch_avatar_block.switch_gravatar', array() );
		}
	}
	// Gravatar MOD
	else
	{
		if ( $userdata['user_allowavatar'] && $config['allow_gravatar_only'] && $config['allow_gravatar'] )
		{			
			$template->assign_block_vars('switch_avatar_block', array() );		
			$template->assign_block_vars('switch_avatar_block.switch_gravatar', array());
		}
	}
}

$template->pparse('body');

page_footer();

?>